import React, { useState } from "react";
import {
  View,
  Text,
  Modal,
  Pressable,
  TextInput,
  KeyboardAvoidingView,
  Platform,
  StyleSheet,
  ColorValue,
} from "react-native";
import { useTheme } from "@/contexts/ThemeContext";

interface InputModalProps {
  visible: boolean;
  onClose: () => void;
  title: string;
  initialValue: string;
  placeholder?: string;
  hint?: string;
  multiline?: boolean;
  maxLength?: number;
  keyboardType?: "default" | "numeric" | "email-address";
  validator?: (value: string) => boolean;
  errorMessage?: string;
  onSave: (value: string) => void;
}

const InputModal: React.FC<InputModalProps> = ({
  visible,
  onClose,
  title,
  initialValue,
  placeholder,
  hint,
  multiline = false,
  maxLength,
  keyboardType = "default",
  validator,
  errorMessage,
  onSave,
}) => {
  const { colors } = useTheme();
  const [inputValue, setInputValue] = useState(initialValue);
  const [error, setError] = useState<string | null>(null);

  // 处理可能的对象类型
  const getBorderColor = (): ColorValue => {
    if (error) return "red";
    return typeof colors.border === "string"
      ? colors.border
      : colors.border.light;
  };

  const getBackgroundColor = (): ColorValue => {
    return typeof colors.backgroundLight === "string"
      ? colors.backgroundLight
      : colors.background;
  };

  const handleSave = () => {
    if (validator && !validator(inputValue)) {
      setError(errorMessage || "输入格式不正确");
      return;
    }

    onSave(inputValue);
    onClose();
  };

  const styles = StyleSheet.create({
    modalOverlay: {
      flex: 1,
      justifyContent: "flex-end",
      backgroundColor: "rgba(0, 0, 0, 0.5)",
    },
    keyboardAvoidView: {
      flex: 1,
      justifyContent: "center",
    },
    inputModal: {
      padding: 20,
      borderTopLeftRadius: 12,
      borderTopRightRadius: 12,
      backgroundColor: colors.background,
    },
    modalTitle: {
      fontSize: 18,
      fontWeight: "bold",
      marginBottom: 12,
      color: colors.text.primary,
    },
    input: {
      borderWidth: 1,
      borderRadius: 8,
      paddingHorizontal: 12,
      fontSize: 16,
      marginBottom: 8,
      borderColor: getBorderColor(),
      color: colors.text.primary,
      backgroundColor: getBackgroundColor(),
    },
    multilineInput: {
      height: 120,
      paddingVertical: 12,
      textAlignVertical: "top",
    },
    singleLineInput: {
      height: 50,
      paddingVertical: 0,
    },
    errorText: {
      fontSize: 12,
      marginTop: 4,
      marginBottom: 8,
      paddingHorizontal: 16,
      color: "red",
    },
    inputHint: {
      fontSize: 13,
      marginBottom: 16,
      color: colors.text.secondary,
    },
    saveButton: {
      paddingVertical: 12,
      borderRadius: 8,
      alignItems: "center",
      backgroundColor: colors.primary,
    },
    saveText: {
      fontSize: 16,
      fontWeight: "bold",
      color: "#FFFFFF",
    },
    cancelButton: {
      paddingVertical: 12,
      borderRadius: 8,
      alignItems: "center",
      backgroundColor: getBackgroundColor(),
      marginTop: 8,
    },
    cancelText: {
      fontSize: 16,
      fontWeight: "bold",
      color: colors.text.primary,
    },
  });

  return (
    <Modal
      transparent
      animationType="slide"
      visible={visible}
      onRequestClose={onClose}
    >
      <Pressable style={styles.modalOverlay} onPress={onClose}>
        <KeyboardAvoidingView
          behavior={Platform.OS === "ios" ? "padding" : undefined}
          style={styles.keyboardAvoidView}
        >
          <Pressable>
            <View style={styles.inputModal}>
              <Text style={styles.modalTitle}>{title}</Text>
              <TextInput
                style={[
                  styles.input,
                  multiline ? styles.multilineInput : styles.singleLineInput,
                ]}
                placeholder={placeholder}
                value={inputValue}
                onChangeText={(text) => {
                  setInputValue(text);
                  setError(null);
                }}
                placeholderTextColor={colors.text.secondary}
                keyboardType={keyboardType}
                maxLength={maxLength}
                autoCapitalize="none"
                autoCorrect={false}
                multiline={multiline}
                textAlignVertical={multiline ? "top" : "center"}
              />
              {error && <Text style={styles.errorText}>{error}</Text>}
              {hint && <Text style={styles.inputHint}>{hint}</Text>}
              <Pressable style={styles.saveButton} onPress={handleSave}>
                <Text style={styles.saveText}>保存</Text>
              </Pressable>
              <Pressable style={styles.cancelButton} onPress={onClose}>
                <Text style={styles.cancelText}>取消</Text>
              </Pressable>
            </View>
          </Pressable>
        </KeyboardAvoidingView>
      </Pressable>
    </Modal>
  );
};

export default InputModal;
